package com.spring.arch.common.core.configuration;

import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

/**
 * Hazelcast缓存核心配置
 * 
 * @author Frank
 * @version 1.0.0.1
 * @since JDK 1.8
 */
@ConditionalOnClass(Hazelcast.class)
@ConditionalOnProperty(prefix = "hazelcast", value = "enable", matchIfMissing = true)
@EnableConfigurationProperties(HazelcastProperties.class)
@Configuration
public class HazelcastServerConfiguration {

    private final HazelcastProperties hazelcastProperties;

    @Autowired
    public HazelcastServerConfiguration(final HazelcastProperties hazelcastProperties) {
        this.hazelcastProperties = hazelcastProperties;
    }

    @Order(10001)
    @Bean
    @ConditionalOnMissingBean
    public CacheManager cacheManager() {
        return new com.hazelcast.spring.cache.HazelcastCacheManager(this.hazelcastServerInstance());
    }

    @Bean(name = "hazelcastServerInstance", destroyMethod = "shutdown")
    public HazelcastInstance hazelcastServerInstance() {
        final Config config = new Config();
        final HazelcastServerProperties server01 = this.hazelcastProperties.getCacheServer();

        config.setInstanceName(server01.getInstanceName());
        if (server01.isManagementCenterEnabled()) {
            config.getManagementCenterConfig().setEnabled(server01.isManagementCenterEnabled())
                .setUpdateInterval(server01.getManagementCenterUpdateInterval())
                .setUrl(server01.getManagementCenterUrl());
        }

        config.setNetworkConfig(server01.buildNetworkConfig());
        config.getGroupConfig().setName(server01.getGroupName());
        // .setGroupPassword(server01.getGroupPassword());
        return Hazelcast.newHazelcastInstance(config);
    }
}
